package com.foodie;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;

public class lei {

    HashMap<String, Object> classMap;

    @Before
    public void before() {
        classMap = new HashMap<>();
        InputStream resourceAsStream = lei.class.getClassLoader().getResourceAsStream("beans.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> elementList = document.selectNodes("//bean");
            for (Element element : elementList) {
                String id = element.attributeValue("id");
                String className = element.attributeValue("class");
                Class<?> resultClass = Class.forName(className);
                Field[] declaredFields = resultClass.getDeclaredFields();
                for (Field declaredField : declaredFields) {
                    System.out.println(declaredField.getName());
                }
                Method[] declaredMethods = resultClass.getDeclaredMethods();
                for (Method declaredMethod : declaredMethods) {
                    System.out.println(declaredMethod.getName());
                }
                classMap.put(id, resultClass.newInstance());//class.forName返回的类需要实例化才能使用
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

    }

    @Test
    public void test() {
        User user = (User)classMap.get("user");
//        user.setId(1);
//        user.setUserName("lisa");
//        user.setPassword("lisa123");
        System.out.println(user);
    }
}
